<?php

namespace App\Repositories\Manage;

use App\Http\Services\FeieyunService;
use App\Models\Printer;
use App\Models\PrinterTask;
use App\Models\Supplier;
use Exception;

class PrinterRepository
{

    public function getList($filter = [], $pageNum = 2, $pageSize = 10): array
    {
        $res = Printer::query()
            ->when(!empty($filter['keywords']), function ($query) use ($filter) {
                return $query->where("title", "like", "%{$filter['keywords']}%");
            })
            ->orderBy("id", "desc")
            ->paginate($pageSize, "*", null, $pageNum)
            ->toArray();

        $res = filterPaginateData($res);

        foreach ($res['items'] as $k => &$v) {
            $v['shop_title'] = Supplier::query()->where("id", intval($v['shop_id']))->value("title");
        }

        return $res;
    }

    public function getOne($id = 0)
    {
        return Printer::query()->where(['id' => intval($id)])->first();
    }

    public function saveOrUpdate($data = [], $id = 0)
    {
        if (!empty($data['id']))
            unset($data['id']);

        if (intval($id)) {
            Printer::where("id", $id)->update($data);
        } else {
            $res = Printer::create($data);
            $id = $res['id'] ?? "";
        }

        //添加新的设备
        if (!empty($id)) {
            $p_str = [];
            !empty($data['sn']) && $p_str[] = trim($data['sn']);
            !empty($data['secret']) && $p_str[] = trim($data['secret']);
            !empty($data['title']) && $p_str[] = trim($data['title']);

            //权限 - 店铺角色是否权限
            (new FeieyunService(['id' => $id]))->addPrinterList([implode("#", $p_str)]);
        }
        return $id;

    }

    /**
     * 删除
     * @param null $id
     */
    public function deletePrinter($id = null)
    {
        if (!intval($id))
            return retFail("参数错误");

        $res = Printer::query()->where(['id' => $id])->first();

        if (!isset($res))
            return retFail("打印机不存在");

        //权限 - 店铺角色是否权限
        (new FeieyunService(['id' => $id]))->delPrinterSqs();
        PrinterTask::query()->where(['printer_sn' => $id])->delete();
        Printer::query()->where(['id' => intval($id)])->delete();

        return retSuc([], "删除成功");
    }

    /**
     * 清空正在打印的
     * @param null $id
     */
    public function clearPrinter(int $id = 0)
    {
        if (!$id)
            return retFail("参数错误");

        $printer = $this->getOne($id);
        if (!isset($printer))
            return retFail("打印机不存在");

        $_printer = new FeieyunService(['id' => $id]);
        $res = $_printer->clearMsg();

        if ($res)
            return retSuc([], "清空成功");

        return retFail("清空失败");
    }

    /**
     * 初始化打印机
     * @param null $id
     */
    public function initPrinter(int $id = 0)
    {
        if (!$id)
            return retFail("参数错误");

        $printer = $this->getOne($id);
        if (!isset($printer))
            return retFail("打印机不存在");

        $feie = new FeieyunService(['id' => $id]);
        $glist = array(
            'orderid' => '4-14F',
            'keshi' => "耳鼻喉科",
            'remark' => '不要加辣！！！',
            'name' => '张三先生',
            'tel' => '13800138000',
            'z_number' => '五号桌',
            'goods' => array(
                '0' => array('title' => '可乐鸡翅', 'price' => '100.4', 'num' => '10')
            ),
        );

        $num = count($glist['goods']);
        $i = 1;
        $content = '';

        try {
            foreach ($glist['goods'] as $key => $value) {
                $content = '<DIRECTION>0</DIRECTION>';
                $content .= '<SIZE>50,80</SIZE>'; //新打印机需要初始化尺寸
                $content .= '<TEXT x="20" y="50" font="12" w="2" h="2" r="0">' . $this->Label_LR($glist['orderid'], "职工", 16) . '</TEXT>';
                $content .= '<TEXT x="20" y="110" font="12" w="2" h="2" r="0">' . $this->Label_LR($glist['keshi'], ($i . '/' . $num), 16) . '</TEXT>';

                $content .= '<TEXT x="20" y="130" font="12" w="1" h="1" r="0"></TEXT>';
                $content .= '<TEXT x="20" y="180" font="12" w="1" h="1" r="0">' . $glist['name'] . '    ' . $glist['tel'] . '</TEXT>';

                $content .= '<TEXT x="20" y="220" font="12" w="1" h="1" r="0">----------------------------------</TEXT>';
                $content .= '<TEXT x="20" y="270" font="12" w="2" h="2" r="0">' . $value["title"] . '</TEXT>';

                $content .= '<TEXT x="20" y="470" font="12" w="1" h="1" r="0">----------------------------------</TEXT>';
                $content .= '<TEXT x="20" y="520" font="12" w="2" h="2" r="0">' . $glist['remark'] . '</TEXT>';

                $i += 1;
                // printLabelMsg(XXXXXXXXX,$content,1);//打开注释调用标签打印接口打印
                $feie->printLabelMsg($content, 1);
            }

            return retSuc([], "初始化成功");
        } catch (Exception $e) {
            return retFail($e->getMessage() || "初始化失败");
        }
    }


    /**
     * [统计字符串字节数补空格，实现左右排版对齐]
     * @param  [string] $str_left    [左边字符串]
     * @param  [string] $str_right   [右边字符串]
     * @param  [int]    $length      [输入当前纸张规格一行所支持的最大字母数量]
     *                               58mm的机器,一行打印16个汉字,32个字母;76mm的机器,一行打印22个汉字,33个字母,80mm的机器,一行打印24个汉字,48个字母
     *                               标签机宽度50mm，一行32个字母，宽度40mm，一行26个字母
     * @return [string]              [返回处理结果字符串]
     */
    function Label_LR($str_left, $str_right, $length)
    {
        if (empty($str_left) || empty($str_right) || empty($length)) return '请输入正确的参数';
        $kw = '';
        $str_left_lenght = strlen(iconv("UTF-8", "GBK//IGNORE", $str_left));
        $str_right_lenght = strlen(iconv("UTF-8", "GBK//IGNORE", $str_right));
        $k = $length - ($str_left_lenght + $str_right_lenght) - 1;
        for ($q = 0; $q < $k; $q++) {
            $kw .= ' ';
        }
        return $str_left . $kw . $str_right;
    }

    /**
     * 打印任务
     */
    public function getTasks($filter = [], $pageNum = 2, $pageSize = 10): array
    {

        $res = PrinterTask::query()
            ->from("printer_task as pt")
            ->join("printer as p", "p.id", "=", "pt.printer_sn")
            ->join("supplier as s", "s.id", "=", "pt.supplier_id")
            ->orderBy("pt.id", "desc")
            ->paginate($pageSize, ["pt.*", "s.title as shop_title", "p.title as printer_title"], null, $pageNum)
            ->toArray();

        return filterPaginateData($res);
    }
}
